/**
 * 
 */
package org.xteam.box2text;

import java.util.ArrayList;
import java.util.List;


public class AlignInfo {
	List<Point> columns = new ArrayList<Point>();

	public void add(Point info) {
		columns.add(info);
	}
	
	public int getWidth(int i) {
		return columns.get(i).x();
	}

	public void fixColumnWidths(int hs, int availableSpace) {
		int space = availableSpace - fixedWidth(hs);
    	int variableCount = variableColumns();
    	int width = space / variableCount;
		List<Point> result = new ArrayList<Point>();
		for (Point p : columns) {
			if (p.x() == p.y()) {
				result.add(new Point(p.x(), p.x()));
			} else if (p.x() >= width) {
				space -= p.x();
				--variableCount;
				result.add(new Point(p.x(), p.x()));
			} else if (p.y() <= width) {
				space -= p.y();
				--variableCount;
				result.add(new Point(p.y(), p.y()));
			} else {
				space -= width;
				--variableCount;
				result.add(new Point(width, width));
			}
		}
		columns = result;
	}

	public void fixColumnWidthsMaximal() {
		List<Point> result = new ArrayList<Point>();
		for (Point p : columns) {
			result.add(new Point(p.y(), p.y()));
		}
		columns = result;
	}
	
	public void fixColumnWidthsMinimal() {
		List<Point> result = new ArrayList<Point>();
		for (Point p : columns) {
			result.add(new Point(p.x(), p.x()));
		}
		columns = result;
	}

	private int variableColumns() {
		int count = 0;
		for (Point p : columns) {
			if (p.x() != p.y()) {
				++count;
			} 
		}
		return count;
	}

	private int fixedWidth(int hs) {
		int width = 0;
		boolean isFirst = true;
		for (Point p : columns) {
			if (isFirst) {
				isFirst = false;
				if (p.x() == p.y()) {
					width = p.x();
				} else {
					width = 0;
				}
			} else {
				if (p.x() == p.y()) {
					width += hs + p.x();
				} else {
					width += hs;
				}
			}
		}
		return width;
	}

	public int minimalWidth(int hs) {
		int min = 0;
		boolean isFirst = true;
		for (Point p : columns) {
			if (isFirst) {
				isFirst = false;
				min = p.x();
			} else {
				min += hs + p.x();
			}
		}
		return min;
	}

	public int maximalWidth(int hs) {
		int max = 0;
		boolean isFirst = true;
		for (Point p : columns) {
			if (isFirst) {
				isFirst = false;
				max = p.y();
			} else {
				max += hs + p.y();
			}
		}
		return max;
	}
}